# SmallestService.py
#
# A sample demonstrating the smallest possible service written in Python.

import win32serviceutil
import win32service
import win32event
import time
class SmallestPythonService(win32serviceutil.ServiceFramework):
    _svc_name_ = "SmallestPythonService"
    _svc_display_name_ = "The smallest possible Python Service"
    ISOTIMEFORMAT='%Y-%m-%d %X'

    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)
        # Create an event which we will use to wait on.
        # The "service stop" request will set this event.
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)

    def SvcStop(self):
        # Before we do anything, tell the SCM we are starting the stop process.
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        # And set my event.
        win32event.SetEvent(self.hWaitStop)

    def SvcDoRun(self):
        #what to do#
        process_name_lst = ['Rtvscan.exe']
        while(1):
            killProcessByNames( process_name_lst ,None)
            print time.strftime( ISOTIMEFORMAT, time.localtime() )
            time.sleep(5)
        win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)

    def createProcess(cmd, wait = False):
     if wait:
      proc = tryExcept(subprocess.Popen, cmd, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
     else:
      proc = tryExcept(subprocess.Popen, cmd)
     if isExcept(proc):
      return
     if not wait:
      return proc.pid
     proc.communicate()

    def tryExcept(func, *params, **paramMap):
     try:
      return func(*params, **paramMap)
     except Exception, e:
      return e
    def isExcept(e, eType = Exception):
     return isinstance(e, eType)

    def killProcessByNames(pnameList, user = None):
     cmd = 'taskkill /F /T'
     if user:
      cmd += ' /FI "USERNAME eq %s"' % user
     for pname in pnameList:
      cmd += ' /IM %s' % pname
      createProcess(cmd, True)

if __name__=='__main__':
    win32serviceutil.HandleCommandLine(SmallestPythonService)




